<template>
	<l-page :page.sync="queryParams.pageNum" :page-size.sync="queryParams.pageSize" :total="total" @getList="getList">
		<el-form ref="queryForm" slot="header" :model="queryParams" :inline="true" label-position="right" label-width="90px">
			<el-form-item label="商品ID:">
				<el-input v-model.trim="queryParams.id" placeholder="请输入商品ID" clearable />
			</el-form-item>
			<el-form-item label="商品名称:">
				<el-input v-model.trim="queryParams.name" placeholder="请输入商品名称" clearable />
			</el-form-item>
			<el-form-item label="商品分类:">
				<el-cascader v-model.trim="queryParams.categoryId" expand-trigger="hover" clearable :props="props" placeholder="请选择分类" @change="handleCategoryChange" />
			</el-form-item>
			<el-form-item label="商品状态:">
				<el-select v-model.trim="queryParams.status" placeholder="商品状态">
					<el-option label="全部" :value="undefined" />
					<el-option label="上架" :value="1" />
					<el-option label="下架" :value="0" />
				</el-select>
			</el-form-item>
			<start-end-time ref="child" :get-time="getTime" title="创建时间:"></start-end-time>
			<el-form-item>
				<div class="page-search-btn">
					<el-button icon="el-icon-search" type="primary" @click="handleQuery">搜索</el-button>
					<el-button icon="el-icon-refresh" type="primary" plain @click="resetQuery">重置</el-button>
				</div>
			</el-form-item>
		</el-form>
		<div slot="options" class="btn-box flex items-center">
			<el-button v-hasPermi="['mall:supplier-goods:add']" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
			<div v-has-permi="['mall:supplier-goods:audit-list']" class="right !mb-0" @click="goAudit">
				待审核商品：<span style="color: #f14a46">{{ auditGoods }}</span
				><span style="color: #6373ee">（点击此处进行审核）</span>
			</div>
		</div>

		<el-tabs v-model="tabActive" class="tabs">
			<el-tab-pane v-for="(item, index) in tabData" :key="index" :label="item.label + `（${tabStatistics[item.key]}）`" :name="item.key"></el-tab-pane>
		</el-tabs>
		<el-table ref="goodsDown" v-loading="loading" stripe :data="goodsList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
			<el-table-column :formatter="emptyToString" type="index" width="55" align="center" label="序号" />
			<el-table-column :formatter="emptyToString" align="center" label="商品ID" prop="id" />
			<el-table-column :formatter="emptyToString" align="center" label="商品名称" width="150px" prop="goods_name" show-overflow-tooltip>
				<template slot-scope="scope">
					<div class="goods-name-style">
						{{ scope.row.name }}
					</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品图片">
				<template slot-scope="scope">
					<el-image style="width: 60px; height: 60px" :src="scope.row.picUrl" :preview-src-list="[scope.row.picUrl]"> </el-image>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品分类" min-width="156">
				<template slot-scope="scope">
					{{ scope.row.topCategoryName + ' > ' + scope.row.categoryName }}
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品价格" prop="retailPrice" sortable min-width="120">
				<template slot-scope="scope">
					<div>{{ scope.row.retailPrice || 0 }}</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToNumber" align="center" label="供应价格" prop="supplyPrice" sortable min-width="120" />
			<!--			<el-table-column :formatter="emptyToNumber" align="center" label="抵扣金额" prop="deductPrice" sortable min-width="120" />-->
			<el-table-column :formatter="emptyToNumber" align="center" label="销量" prop="commoditySales" />
			<el-table-column :formatter="emptyToNumber" align="center" label="商品库存" prop="inventory" sortable min-width="120">
				<template slot-scope="scope">
					<div>{{ scope.row.inventory || 0 }}</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="审核状态">
				<template slot-scope="scope">
					<div>审核成功</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品状态">
				<template slot-scope="scope">
					<el-switch
						v-model.trim="scope.row.status"
						:active-value="1"
						:inactive-value="0"
						active-text="上架"
						inactive-text="下架"
						class="switch"
						@change="handleUpdateStatus(scope.row, scope.row.status)"
					></el-switch>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="创建时间" prop="createTime" min-width="156">
				<template slot-scope="scope">
					<div class="w-full flex flex-col items-center">
						<span>{{ dayjs(scope.row.createTime).format('YYYY-MM-DD') }}</span>
						<span>{{ dayjs(scope.row.createTime).format('HH:mm:ss') }}</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="操作" width="150" fixed="right">
				<template slot-scope="scope">
					<div class="table-action flex justify-center">
						<el-button v-hasPermi="['mall:supplier-goods:edit']" type="primary" @click="handleUpdate(scope.row)">编辑 </el-button>
						<el-button v-hasPermi="['mall:supplier-goods:remove']" type="danger" @click="handleDelete(scope.row)">删除 </el-button>
					</div>
				</template>
			</el-table-column>
		</el-table>
	</l-page>
</template>

<script>
import { addGoods, updateGoods, exportGoods, getSupplierGoods, delSupplier, downGoods, upGoods, getAuditGoods } from '@/api/mall/goods';
import { listChild, listParent } from '@/api/mall/category';
import tableMixins from '@/mixins/table';

export default {
	name: 'Goods',
	components: {},
	mixins: [tableMixins],
	data() {
		return {
			tabActive: 'totalCount',
			tabData: [
				{
					label: '全部',
					name: null,
					key: 'totalCount',
				},
				{
					label: '上架',
					name: 1,
					key: 'waitCount',
				},
				{
					label: '下架',
					name: 0,
					key: 'refuseCount',
				},
			],
			tabStatistics: {
				auditAmount: 0,
				auditCount: 0,
				refuseAmount: 0,
				refuseCount: 0,
				totalCount: 0,
				waitAmount: 0,
				waitCount: 0,
			},
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 商品基本信息表格数据
			goodsList: [],
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			// 搜索参数
			queryParams: {
				current: 1,
				size: 10,
				goodsSn: null,
				name: null,
				categoryId: null,
				brandId: null,
				gallery: null,
				keywords: null,
				brief: null,
				isOnSale: null,
				sortOrder: null,
				picUrl: null,
				shareUrl: null,
				isNew: null,
				isHot: null,
				unit: null,
				counterPrice: null,
				retailPrice: null,
				detail: null,
				status: null,
				goodsType: null,
			},
			status: '',
			// 表单参数
			form: {},
			auditGoods: 0,
			// 表单校验
			rules: {
				goodsSn: [{ required: true, message: '商品编号不能为空', trigger: 'blur' }],
				name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
			},

			goodsDetail: '',
			detailDialogVisible: false,
			goodsTypeList: [],
			props: {
				expandTrigger: 'click',
				lazy: true,
				lazyLoad(node, resolve) {
					const { level, value } = node;
					if (level === 0) {
						listParent().then((response) => {
							const { data } = response;
							const nodes = data.map((item) => ({
								value: item.id,
								label: item.name,
								leaf: false,
							}));
							resolve(nodes);
						});
					} else {
						listChild(value).then((response) => {
							const { data } = response;
							const nodes = data.map((item) => ({
								value: item.id,
								label: item.name,
								leaf: true,
							}));
							resolve(nodes);
						});
					}
				},
			},
		};
	},
	watch: {
		tabActive() {
			const item = this.tabData.find((item) => item.key === this.tabActive);
			this.queryParams.status = item.name;
			this.handleQuery();
		},
	},
	created() {
		this.getList();
		this.getDicts('mall_goods_type').then((response) => {
			this.goodsTypeList = response.data;
		});
		this.getStatisticsV2();
		this.getAuditList();
	},
	methods: {
		getAuditList() {
			this.$request
				.get('/mall/supplier-goods/queryAuditCount', {
					current: 1,
					size: 10,
				})
				.then((res) => {
					this.auditGoods = res.data[0];
				});
		},
		getStatisticsV2() {
			this.$request.get('/mall/supplier-goods/queryCount').then((res) => {
				this.tabStatistics = {
					totalCount: res.data[0],
					waitCount: res.data[1],
					refuseCount: res.data[2],
				};
			});
		},
		goAudit() {
			this.$router.push({
				path: '/goods/supplierGoodsAudit',
			});
		},
		getTime(startTime, endTime) {
			this.queryParams.startCreateTime = startTime;
			this.queryParams.endCreateTime = endTime;
		},
		change(value) {
			for (let key in this.cobj) {
				console.log();
				if (value.indexOf(key) == -1) {
					this.$set(this.cobj, key, false);
				} else {
					this.$set(this.cobj, key, true);
				}
			}
		},
		/** 搜索商品基本信息列表 */
		editInventory(id) {
			this.$prompt('请输入需要编辑的库存数量', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputPattern: /(^[0-9]\d*$)/,
				inputErrorMessage: '请输入正整数(包含0)',
			})
				.then(({ value }) => {
					updateGoods({ id, inventory: Number(value) }).then(() => {
						this.$message.success('编辑成功!');
						this.getList();
					});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '取消输入',
					});
				});
		},
		editPrice(id) {
			this.$prompt('请输入需要编辑的价格', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputPattern: /(^\d+$)|(^\d+\.\d+$)/,
				inputErrorMessage: '请输入正数',
			})
				.then(({ value }) => {
					updateGoods({ id, retailPrice: Number(value) }).then(() => {
						this.$message.success('编辑成功!');
						this.getList();
					});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '取消输入',
					});
				});
		},
		getList() {
			this.loading = true;
			getSupplierGoods(this.queryParams).then((response) => {
				this.goodsList = response.data.records;
				this.total = response.data.total;
				this.loading = false;
			});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				goodsSn: null,
				name: null,
				categoryId: null,
				brandId: null,
				gallery: null,
				keywords: null,
				brief: null,
				isOnSale: null,
				sortOrder: null,
				picUrl: null,
				shareUrl: null,
				isNew: null,
				isHot: null,
				unit: null,
				counterPrice: null,
				retailPrice: null,
				detail: null,
				delFlag: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
			};
			this.resetForm('form');
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.current = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.queryParams = {
				current: 1,
				size: 10,
			};
			this.$refs.child.resetTime();
			this.resetForm('queryForm');
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id);
			this.single = selection.length !== 1;
			this.multiple = !selection.length;
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.$router.push('/goods/supplierAddGoods');
		},
		/** 编辑按钮操作 */
		handleUpdate(row) {
			this.reset();
			this.$router.push({
				path: '/goods/supplierAddGoods?id=' + row.id,
			});
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs['form'].validate((valid) => {
				if (valid) {
					if (this.form.id != null) {
						updateGoods(this.form).then((response) => {
							this.msgSuccess('编辑成功');
							this.open = false;
							this.getList();
						});
					} else {
						addGoods(this.form).then((response) => {
							this.msgSuccess('新增成功');
							this.open = false;
							this.getList();
						});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			this.$confirm('是否删除商品ID为"' + row.id + '"的商品?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return delSupplier(row.id);
				})
				.then(() => {
					this.getList();
					this.msgSuccess('删除成功');
				});
		},
		/** 导出按钮操作 */
		handleExport() {
			const queryParams = this.queryParams;
			this.$confirm('是否确认导出所有商品基本信息数据项?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return exportGoods(queryParams);
				})
				.then((response) => {
					this.download(response.msg);
				});
		},
		showDetail(detail) {
			this.goodsDetail = detail;
			this.detailDialogVisible = true;
		},
		handleUpdateStatus(row, status) {
			console.log(status);
			if (status == 1) {
				upGoods([row.id]).then((res) => {
					this.$message.success('上架成功!');
					this.getList();
				});
			} else if (row.status == 0) {
				downGoods([row.id]).then((res) => {
					this.$message.success('下架成功!');
					this.getList();
				});
			}
		},
		handleCategoryChange(value) {
			this.queryParams.categoryId = value[value.length - 1];
		},
		batchPutAway(row) {
			let currentSelect = this.$refs.goodsDown.selection;
			let itemArr = [];
			if (currentSelect.length < 1) {
				this.$message.error('请选择商品!');
				return;
			}
			for (let i = 0; i < currentSelect.length; i++) {
				itemArr.push(currentSelect[i].id);
			}

			upGoods(itemArr).then((res) => {
				this.$message.success('上架成功!');
				this.getList();
			});
		},
		batchSoldOut(row) {
			let currentSelect = this.$refs.goodsDown.selection;
			let itemArr = [];

			if (currentSelect.length < 1) {
				this.$message.error('请选择商品!');
				return;
			}
			for (let i = 0; i < currentSelect.length; i++) {
				itemArr.push(currentSelect[i].id);
			}
			downGoods(itemArr).then((res) => {
				this.$message.success('下架成功!');
				this.getList();
			});
		},
	},
};
</script>

<style scoped lang="scss">
.btn-box {
	display: flex;
	justify-content: space-between;
	align-items: center;

	.right {
		width: 321px;
		height: 36px;
		background: #eff0ff;
		border: 1px solid #c9d0ff;
		opacity: 1;
		border-radius: 5px;
		font-size: 12px;
		padding-left: 16px;
		box-sizing: border-box;
		line-height: 36px;
		cursor: pointer;
	}
}
</style>
